// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
@file:JvmName("PlatformAnalyzerServicesUtils")
package org.jetbrains.kotlin.idea.base.projectStructure.compositeAnalysis

import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.analyzer.common.CommonPlatformAnalyzerServices
import org.jetbrains.kotlin.js.resolve.JsPlatformAnalyzerServices
import org.jetbrains.kotlin.platform.*
import org.jetbrains.kotlin.platform.isWasm
import org.jetbrains.kotlin.platform.TargetPlatform
import org.jetbrains.kotlin.platform.WasmPlatform
import org.jetbrains.kotlin.platform.jvm.JvmPlatform
import org.jetbrains.kotlin.platform.jvm.isJvm
import org.jetbrains.kotlin.platform.konan.NativePlatform
import org.jetbrains.kotlin.platform.konan.isNative
import org.jetbrains.kotlin.platform.wasm.*
import org.jetbrains.kotlin.resolve.*
import org.jetbrains.kotlin.resolve.jvm.platform.JvmPlatformAnalyzerServices
import org.jetbrains.kotlin.resolve.konan.platform.NativePlatformAnalyzerServices
import org.jetbrains.kotlin.wasm.resolve.WasmJsPlatformAnalyzerServices
import org.jetbrains.kotlin.wasm.resolve.WasmPlatformAnalyzerServices
import org.jetbrains.kotlin.wasm.resolve.WasmWasiPlatformAnalyzerServices
import java.lang.IllegalStateException

fun TargetPlatform.findAnalyzerServices(project: Project): PlatformDependentAnalyzerServices = when {
    isCommon() -> {
        if (project.useCompositeAnalysis)
            CompositeAnalyzerServices(componentPlatforms.map { it.findAnalyzerServices() })
        else
            CommonPlatformAnalyzerServices
    }
    isJvm() -> JvmPlatformAnalyzerServices
    isJs() -> JsPlatformAnalyzerServices
    isWasmJs() -> WasmPlatformAnalyzerServices
    isWasmWasi() -> WasmWasiPlatformAnalyzerServices
    isWasm() -> WasmPlatformAnalyzerServices
    isNative() -> NativePlatformAnalyzerServices
    else -> throw IllegalStateException("Unknown platform $this")
}

fun SimplePlatform.findAnalyzerServices(): PlatformDependentAnalyzerServices = when (this) {
    is JvmPlatform -> JvmPlatformAnalyzerServices
    is JsPlatform -> JsPlatformAnalyzerServices
    is WasmPlatformWithTarget -> {
        when(this.target) {
            WasmTarget.JS -> WasmJsPlatformAnalyzerServices
            WasmTarget.WASI -> WasmWasiPlatformAnalyzerServices
        }
    }
    is WasmPlatform -> WasmPlatformAnalyzerServices
    is NativePlatform -> NativePlatformAnalyzerServices
    else -> throw IllegalStateException("Unknown platform $this")
}
